<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="queryData" layout="inline">
            <a-form-item label="纱支单位" v-if="id == 1 && permissionStore.hasPermisson('szdw.cx')">
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="dataForm.yarnTypeNames"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="pageData.btnList"
            @select="selectHanler"
            @add="addHandler"
            @del="deleteHandler"
            @export="exportExcel"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs :lazy-load="true" :justify="true" default-active-key="1" @change="handoff">
        <template #extra>
          <Toolbar
            style="position: absolute; right: 0"
            :items="tabBtnList"
            @import="importHandler"
            @excel="downloadHandler"
          >
          </Toolbar>
        </template>
        <a-tab-pane title="纱支单位" key="1">
          <!-- <div style="float: right;">
            <Toolbar :items="pageData.btnList1" @import="importHandler" @excel="downloadHandler">
            </Toolbar>
          </div> -->
          <a-spin
            :loading="pageData.pageLoading"
            tip="加载中"
            dot
            style="height: 100%; width: 100%; z-index: 999"
          >
            <div style="width: 100%; height: 100%">
              <encapsulation-agrid
                ref="table1Ref"
                :configaggrid="configTable1"
              ></encapsulation-agrid>
            </div>
          </a-spin>
        </a-tab-pane>
        <a-tab-pane title="纱支" key="2">
          <!-- <div style="float: right;">
            <Toolbar :items="pageData.btnList1" @import="importHandler" @excel="downloadHandler">
            </Toolbar>
          </div> -->
          <a-spin
            :loading="pageData.pageLoading"
            tip="加载中"
            dot
            style="height: 100%; width: 100%; z-index: 999"
          >
            <div style="width: 100%; height: 100%">
              <encapsulation-agrid
                ref="table2Ref"
                :configaggrid="configTable2"
              ></encapsulation-agrid>
            </div>
          </a-spin>
        </a-tab-pane>
      </a-tabs>
    </template>
    <a-drawer
      v-if="id == 1"
      style="z-index: 999"
      :drawer-style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData.showAdd"
      :ok-loading="pageData.pageLoading"
      unmountOnClose
      @ok="sideOk"
      @cancel="sideNo"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <!-- <a-form-item
            label-col-flex="120px"
            v-if="id == 1"
            label="纱支单位编号"
            field="typeCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" @blur="inputBlur" v-model.trim="dataForm.typeCode" />
          </a-form-item> -->
          <a-form-item
            label-col-flex="120px"
            label="纱支单位"
            field="typeName"
            :rules="[{ required: true, message: '类别必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="dataForm.typeName" />
          </a-form-item>
          <a-form-item label-col-flex="120px" label="备注" field="remark">
            <!-- <a-input class="bacClass" v-model="dataForm.remark" /> -->
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <a-drawer
      v-else
      :drawer-style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      :visible="pageData2.showAdd"
      :ok-loading="pageData.pageLoading"
      unmountOnClos
      @ok="sideOk1"
      @cancel="sideNo2"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData2.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <!-- <a-form-item label="纱支类别" field="yarnTypeName" :rules="[{ required: true, message: '纱支类别必选' }]"
                                 :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" :loading="loadings" @search="handleSearch12" @focus="focusSel" :filter-option="false"
                                  allow-search v-model.trim="dataForm.yarnTypeName" allow-clear placeholder="请输入纱支类别">
                            <a-option v-for="item in pageData.yarnTypeNames as any"  :value="item.typeName">{{
                                item.typeName
                                }}
                            </a-option>
                        </a-select>
                    </a-form-item> -->
          <!-- <a-form-item
            label="编号"
            field="yarnCode"
            label-col-flex="100px"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" @blur="inputBlur1" v-model.trim="dataForm.yarnCode" />
          </a-form-item> -->
          <!-- { validator: isYarnCount },  -->
          <a-form-item
            label="纱支"
            field="yarnCount"
            label-col-flex="100px"
            :rules="[{ required: true, message: '纱支必填' }]"
            :validate-trigger="['blur']"
          >
            <a-input class="bacClass" v-model.trim="dataForm.yarnCount" />
          </a-form-item>
          <a-form-item
            label="纱支单位"
            :rules="[{ required: true, message: '纱支必填' }]"
            :validate-trigger="['blur']"
            label-col-flex="100px"
            field="yarnUnit"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              :loading="loadings12"
              @search="handleSearch12"
              @focus="focusSel"
              :filter-option="false"
              allow-search
              v-model.trim="dataForm.yarnUnit"
              allow-clear
            >
              <a-option v-for="item in pageData.yarnTypeNames as any" :value="item.typeName"
                >{{ item.typeName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="备注" field="remark" label-col-flex="100px">
            <!-- <a-input class="bacClass" v-model="dataForm.remark" /> -->
            <a-textarea
              class="bacClass"
              placeholder=""
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import { post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import { indexOf } from 'lodash'
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import { exportStyleExcel } from '@/api/Export2StyleExcel'

  interface Cloth {
    code: string
  }

  interface ClothInfo {
    id: any
    // yarnCode: any
    code: any
    typeName: any
    remark: any
    isDelete: any
    createName: any
    createTime: any
    updateName: any
    updateTime: any
    property: any
    yarnTypeId: any
    yarnTypeName: any
    num: any
    coefficient: any
    typeCode: any
    yarnTypeNames: any
    unit: any
    yarnCount: any
    yarnUnit: any
  }

  export default {
    name: 'Categoriesofyarncount',
    setup() {
      let cxbl = ''
      const selectHanler = () => {
        if (id.value == 1) {
          pagination.page = 1
          cxbl = dataForm.yarnTypeNames
          doRefresh()
        } else if (id.value == 2) {
          paginations.page = 1
          cxbl = dataForm.yarnTypeNames
          doRefresh2()
        }
      }
      const table1Ref = ref<any>(null)
      const tableColumns = [
        {
          title: '纱支单位序号',
          key: 'typeCode',
          dataIndex: 'typeCode',
          width: 150,
        },
        {
          title: '纱支单位',
          key: 'typeName',
          dataIndex: 'typeName',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },

        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          key: 'edit',
          dataIndex: 'edit',
          slotName: 'edit',
          width: 150,
          fixed: 'right',
        },
      ]
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        obj['width'] = 250
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 90
          obj['cellRenderer'] = {
            template: `
            <a-tag class="tagCss" v-if="e" @click="a">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                e: pageData.isEdit,
                a,
              }
            },
          }
        }

        return obj
      })
      tc.unshift({
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      })
      let configTable1 = {
        url: 'product/yarnType/getYarnTypePage', //接口路径
        queryData: {
          //接口参数
          deleteState: 0,
          typeName: cxbl,
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tc,
        fileName: 'Categoriesofyarncount',
      }
      const table2Ref = ref<any>(null)
      const tableColumns2 = [
        {
          title: '纱支序号',
          key: 'yarnCode',
          dataIndex: 'yarnCode',
          width: 150,
        },
        {
          title: '纱支',
          key: 'yarnCount',
          dataIndex: 'yarnCount',
          width: 150,
        },
        {
          title: '纱支单位',
          key: 'yarnUnit',
          dataIndex: 'yarnUnit',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          key: 'edit',
          dataIndex: 'edit',
          slotName: 'edit',
          width: 150,
          fixed: 'right',
        },
      ]
      let tc2: any[] = tableColumns2.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        obj['width'] = 250
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 80
          obj['cellRenderer'] = {
            template: `
            <a-tag color="#ff7d00" class="gesture" v-if="e" @click="a">修改</a-tag>`,
            setup(props: any) {
              const a = () => {
                editHandler1(props.params.data)
              }
              return {
                e: pageData.isEdit,
                a,
              }
            },
          }
        }

        return obj
      })
      tc2.unshift({
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      })
      let configTable2 = {
        url: 'product/yarn/getYarnPage', //接口路径
        queryData: {
          //接口参数
          deleteState: 0,
        },
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: true, //点击行是否多选
        column: tc2,
        fileName: 'Categoriesofyarncount-2',
      }

      function PageSize(val: any) {
        if (id.value == 1) {
          pagination.page = val
          doRefresh()
        } else if (id.value == 2) {
          paginations.page = val
          doRefresh2()
        }
      }

      function change1(val: any) {
        if (id.value == 1) {
          pagination.pageSize = val
          doRefresh()
        } else if (id.value == 2) {
          paginations.pageSize = val
          doRefresh2()
        }
      }

      const headerShow = ref<boolean>(true)
      let id = ref(1)
      const handoff = (key: any) => {
        id.value = key
        gridOption2.value.setRowData([])
        if (id.value == 1) {
          doRefresh()
        } else {
          doRefresh2()
        }
        // dataForm.yarnTypeNames = ''
      }
      let tableList1 = ref([])
      let tableList2 = ref([])

      function doRefresh() {
        let typecxbl = typeof cxbl
        if (typecxbl == 'object') {
          cxbl = ''
        }
        table1Ref.value.setQuery({
          deleteState: 0,
          typeName: cxbl,
        })
      }

      function doRefresh2() {
        table2Ref.value.setQuery({
          deleteState: 0,
        })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const paginations = usePagination(doRefresh2)
      const table = useTable()
      const rowKey = useRowKey('id')
      const pageData = reactive<{
        clothList: Cloth[]
        showAdd: boolean
        sideTitle: string
        typeName: []
        dropDownData: any
        yarnTypeName: []
        pageLoading: any
        yarnTypeNames: []
        rHeight: number | undefined
        btnList: any[]
        btnList1: any[]
        isEdit: boolean
      }>({
        clothList: [],
        showAdd: false,
        sideTitle: '新增纱支类别',
        typeName: [],
        dropDownData: '',
        yarnTypeName: [],
        pageLoading: false,
        yarnTypeNames: [],
        rHeight: 0,
        btnList: [],
        btnList1: [],
        isEdit: false,
      })
      const pageData2 = reactive<{
        clothList: Cloth[]
        showAdd: boolean
        sideTitle: string
      }>({
        clothList: [],
        showAdd: false,
        sideTitle: '新增纱支类别',
      })
      const pageData3 = reactive<{
        clothList: Cloth[]
        showAdd: boolean
        sideTitle: string
      }>({
        clothList: [],
        showAdd: false,
        sideTitle: '修改纱支',
      })
      //下拉数据
      const options = ref<any>(pageData.yarnTypeName)
      const loadings = ref(false)

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'product/yarnType/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.yarnTypeName = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const focusSel = () => {
        if (id.value == 1) {
          selCxAll12({ typeName: '', deleteState: 0 })
        } else if (id.value == 2) {
          selCxAll12({
            typeName: '',
            deleteState: 0,
          })
        }
      }
      //下拉数据
      const options12 = ref<any>(pageData.yarnTypeNames)
      const loadings12 = ref(false)
      const handleSearch12 = (value: any) => {
        if (value) {
          const ob = { typeName: value, deleteState: 0 }
          loadings12.value = true
          selCxAll12(ob)
          options.value = pageData.yarnTypeNames
          loadings12.value = false
        } else {
          options12.value = []
        }
      }

      //下拉框查询
      function selCxAll12(val: any) {
        post({
          url: 'product/yarnType/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            // (data as string[]).splice(0, 0, "全部");
            pageData.yarnTypeNames = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      //新增里的纱支类别下拉框
      let szTypeName = ref([])
      const options1 = ref<any>(pageData.typeName)
      const loading1 = ref(false)

      const szTyoeNames = (value: any) => {
        post({
          url: 'product/yarnType/getYarnTypeByFirm',
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              szTypeName.value = data
            }
          })
          .catch(console.log)
      }

      onMounted(() => {
        // 切换tap到本页面执行的方法
        emitter.on('Categoriesofyarncount', () => {
          if (id.value == 1) {
            // selCxAll({});
            doRefresh()
          } else if (id.value == 2) {
            // selCxAll({});
            doRefresh2()
          }
        })
      })
      const queryData = reactive({
        clothType: '',
      })

      const addHandler = () => {
        for (let item in dataForm) {
          dataForm[item] = ''
        }
        pageData.yarnTypeName = []
        dataForm.yarnTypeName = ''
        if (id.value == 1) {
          pageData.showAdd = true
          pageData.sideTitle = '新增纱支类别'
        } else if (id.value == 2) {
          pageData2.showAdd = true
          pageData2.sideTitle = '新增纱支'
        }
      }

      const dataForm = reactive<ClothInfo>({
        id: null,
        // yarnCode: '',
        code: '',
        typeName: '',
        remark: '',
        isDelete: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        property: '',
        yarnTypeId: '',
        yarnTypeName: '',
        num: 0,
        coefficient: '',
        typeCode: '',
        yarnTypeNames: '',
        unit: '',
        yarnCount: '',
        yarnUnit: '',
      })

      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }

      const gridOption2 = ref()
      const colState2 = ref()
      const gridReady2 = (params: any) => {
        gridOption2.value = params.api
        colState2.value = params.columnApi
      }

      const formRef = ref<FormInstance>()
      const sideOk = () => {
        //szTyoeNames({});
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true
            if (pageData.sideTitle === '新增纱支类别') {
              let dataForms = {
                typeName: dataForm.typeName,
                // typeCode: dataForm.typeCode,
                remark: dataForm.remark,
              }
              post({
                url: 'product/yarnType/addYarnType',
                data: [dataForms],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    doRefresh()
                    formRef.value?.resetFields()
                    pageData.showAdd = false
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            } else if (pageData.sideTitle === '修改纱支类别') {
              const dataForms = {
                id: dataForm.id,
                // typeCode: dataForm.typeCode,
                typeName: dataForm.typeName,
                remark: dataForm.remark,
              }
              post({
                url: 'product/yarnType/updateYarnType',
                data: [dataForms],
              })
                .then(({ data, code, message }: any) => {
                  if (code === 200) {
                    formRef.value?.resetFields()
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    doRefresh()
                    pageData.showAdd = false
                  } else {
                    Message.success({
                      content: message,
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
      const isArr = ref([])
      const sideOk1 = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            pageData.pageLoading = true
            let id = ''
            pageData.yarnTypeNames.forEach((item: any) => {
              if (item.typeName == dataForm.yarnTypeName) {
                id = item.id
              }
            })
            const dataForms = {
              id: dataForm.id,
              yarnTypeId: id,
              yarnTypeName: dataForm.yarnTypeName,
              property: dataForm.property,
              // yarnCode: dataForm.yarnCode,
              num: dataForm.num,
              coefficient: dataForm.coefficient,
              remark: dataForm.remark,
              unit: dataForm.unit,
              yarnUnit: dataForm.yarnUnit,
              yarnCount: dataForm.yarnCount,
            }
            if (dataForm.id == undefined || dataForm.id == '') {
              dataForms.id = undefined
              post({
                url: 'product/yarn/addyarn',
                data: [dataForms],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    doRefresh2()
                    formRef.value?.resetFields()
                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                    formRef.value?.resetFields()
                    pageData2.showAdd = false
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  pageData.pageLoading = false
                })
                .finally(() => {})
            } else {
              post({
                url: 'product/yarn/updateYarn',
                data: [dataForms],
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    doRefresh2()
                    formRef.value?.resetFields()
                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                    formRef.value?.resetFields()
                    pageData2.showAdd = false
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  pageData.pageLoading = false
                })
                .finally(() => {
                  doRefresh()
                })
            }
          }
        })
      }
      const sideNo = () => {
        pageData.showAdd = false
        formRef.value?.resetFields()
      }
      const sideNo2 = () => {
        pageData2.showAdd = false
        formRef.value?.resetFields()
      }
      const deleteHandler = () => {
        if (id.value == 1 && table1Ref.value.getSelectedRows().length == 0) {
          Message.warning({
            content: '请勾选一条数据',
            duration: 5000,
          })
          return
        }
        if (id.value == 2 && table2Ref.value.getSelectedRows().length == 0) {
          Message.warning({
            content: '请勾选一条数据',
            duration: 5000,
          })
          return
        }
        let asuiArray: any = []
        selectedRowKeys.value.forEach((item: any) => {
          asuiArray.push({
            id: Number(item),
          })
        })
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            if (id.value == 1) {
              post({
                url: 'product/yarnType/delYarnType',
                data: table1Ref.value.getSelectedRows(),
              })
                .then(({ code, data }: any) => {
                  if (code === 200) {
                    pagination.page = 1
                    doRefresh()
                    Message.success({
                      content: '删除成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: '删除失败',
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
              // console.log(selectedRowKeys.value[0])
            } else if (id.value == 2) {
              post({
                url: 'product/yarn/delYarn',
                data: table2Ref.value.getSelectedRows(),
              })
                .then(({ code, data }: any) => {
                  if (code === 200) {
                    paginations.page = 1
                    doRefresh2()
                    Message.success({
                      content: '删除成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: '删除失败',
                      duration: 5000,
                    })
                  }
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            }
          },
        })
      }
      //修改 record（本行数据）
      const editHandler = (record: any) => {
        // dataForm.id = record.id
        // dataForm.typeCode = record.typeCode
        // dataForm.typeName = record.typeName
        // dataForm.remark = record.remark
        for (var key in record) {
          dataForm[key] = record[key]
        }
        //侧滑栏滑出滑入
        pageData.showAdd = true
        pageData.sideTitle = '修改纱支类别'
      }
      //修改 record（本行数据）
      const editHandler1 = (record: any) => {
        // dataForm.id = record.id
        // dataForm.property = record.property
        // dataForm.yarnTypeName = record.yarnTypeName
        // dataForm.num = record.num
        // dataForm.coefficient = record.coefficient
        // dataForm.yarnCode = record.yarnCode
        // dataForm.remark = record.remark
        for (var key in record) {
          dataForm[key] = record[key]
        }
        //侧滑栏滑出滑入
        pageData2.showAdd = true
        pageData2.sideTitle = '修改纱支'
      }
      const isChiese = (value: string, cb: Function) => {
        var a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值只能是英文数字组合或英文，数字！')
          }

          resolve()
        })
      }

      //纱支只能取三位数或四位数
      const shazhiguize = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值只能是英文数字组合或英文，数字！')
          }
          if (value.length == 3 || value.length == 4) {
            resolve()
          } else {
            cb('只能填写三位数字或三位数字加字母')
          }
          resolve()
        })
      }
      let isLetter = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'N',
        'M',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
      ]
      //判断是否符合纱支规则
      const isYarnCount = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') == -1) {
            //判断纱支长度是否超过了4
            let field = value + ''

            if (field.length > 4) {
              cb('纱支不能超过4个字符！')
            } else {
              //判断纱支里是否包含字母
              let regString = /[a-zA-Z]+/
              if (regString.test(field)) {
                //将字母变为大写
                field = field.toUpperCase()
                dataForm.yarnCount = field.toUpperCase()
                //判断包含了多少个字母
                let fieldList = []
                for (var i = 0; i < field.length; i++) {
                  fieldList.push(field[i])
                }
                let list = fieldList.filter(function (o: any) {
                  return isLetter.indexOf(o) != -1
                })
                if (list.length > 1) {
                  cb('纱支不能超过2个字母！')
                  // dataForm.yarnCount=""
                } else {
                  //只包含一个字母 判断字母位置
                  if (!regString.test(field.charAt(field.length - 1))) {
                    cb('字母只能在结尾！')
                    // dataForm.yarnCount=""
                  }
                }
              }
              //判断 纱支长度是否等于4
              if (field.length < 4) {
                //在纱支前面补0
                let differLen = 4 - field.length
                let zeroFill = ''
                for (let i = 0; i < differLen; i++) {
                  zeroFill += '0'
                }
                dataForm.yarnCount = zeroFill + field
              }
            }
          } else {
            cb('填写的值只能是英文数字组合或英文，数字！')
            // dataForm.yarnCount=""
          }
          resolve()
        })
      }
      const inputBlur = () => {
        dataForm.typeCode = dataForm.typeCode.toUpperCase()
      }
      const inputBlur1 = () => {
        dataForm.yarnCode = dataForm.yarnCode.toUpperCase()
      }

      //前端导出
      function exportExcel() {
        if (id.value == 1 && table1Ref.value.getSelectedRows().length == 0) {
          Message.error({
            content: '请先勾选需导出行数据',
            duration: 5000,
          })
          return
        }
        if (id.value == 2 && table2Ref.value.getSelectedRows().length == 0) {
          Message.error({
            content: '请先勾选需导出行数据',
            duration: 5000,
          })
          return
        }
        let header: any = []
        let filterVal: any = []
        let data: any = []
        if (id.value == 2) {
          header = [
            '纱支序号',
            '纱支',
            '纱支单位',
            '备注',
            '创建人',
            '创建时间',
            '最后修改人',
            '最后修改时间',
          ]
          filterVal = [
            'yarnCode',
            'yarnCount',
            'yarnUnit',
            'remark',
            'createName',
            'createTime',
            'updateName',
            'updateTime',
          ]
          data = formatJson(filterVal, table2Ref.value.getSelectedRows())
          exportStyleExcel({ header, data, filename: '纱支.xlsx' })
        } else if (id.value == 1) {
          header = [
            '纱支单位序号',
            '纱支单位',
            '备注',
            '创建人',
            '创建时间',
            '最后修改人',
            '最后修改时间',
          ]
          filterVal = [
            'typeCode',
            'typeName',
            'remark',
            'createName',
            'createTime',
            'updateName',
            'updateTime',
          ]
          data = formatJson(filterVal, table1Ref.value.getSelectedRows())
          exportStyleExcel({ header, data, filename: '纱支单位.xlsx' })
        }
      }

      function formatJson(filterVal: any[], jsonData: any[]) {
        return jsonData.map((v) =>
          filterVal.map((j) => {
            if (v[j]) {
              return v[j]
            } else {
              return ''
            }
          })
        )
      }

      //模板下载
      const downloadHandler = () => {
        if (id.value == 1) {
          axios
            .get(baseURL + '/product/yarnType/uploadModel', {
              responseType: 'blob',
              headers: {
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((res) => {
              if (res.status === 200) {
                filedownload(res.data, '纱支单位.xlsx')
              }
            })
        } else if (id.value == 2) {
          axios
            .get(baseURL + '/product/yarn/uploadModel', {
              responseType: 'blob',
              headers: {
                token: sessionStorage.getItem('USER-TOKEN-KEY'),
              },
            })
            .then((res) => {
              if (res.status === 200) {
                filedownload(res.data, '纱支.xlsx')
              }
            })
        }
      }
      const importHandler = () => {
        const inputEle: HTMLInputElement = document.createElement('input')
        inputEle.type = 'file'
        inputEle.id = 'fileUploadExcel'
        inputEle.accept =
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
        inputEle.addEventListener('change', (e) => {
          const formData = new FormData()
          if (inputEle.files !== null) {
            formData.append('file', inputEle.files[0] || '')
          } else {
            Message.warning('未选择文件！')
            return
          }
          pageData.pageLoading = true

          if (id.value == 1) {
            axios
              .post(baseURL + '/product/yarnType/analyseYarnTypeModel', formData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  token: sessionStorage.getItem('USER-TOKEN-KEY'),
                },
              })
              .then((result) => {
                if (result.data['code'] === 200) {
                  Message.success('导入成功')
                } else {
                  Message.error(result.data.message)
                }
              })
              .finally(() => {
                pageData.pageLoading = false
                doRefresh()
              })
          } else if (id.value == 2) {
            axios
              .post(baseURL + '/product/yarn/analyseYarnDanielModel', formData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  token: sessionStorage.getItem('USER-TOKEN-KEY'),
                },
              })
              .then((result) => {
                if (result.data['code'] === 200) {
                  Message.success('导入成功')
                } else {
                  Message.error(result.data.message)
                }
              })
              .finally(() => {
                pageData.pageLoading = false
                doRefresh2()
              })
          }
        })
        inputEle.click()
      }
      const tabBtnList = ref([])
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()
      //szlb 纱支类别权限  sz纱支权限
      //判断是否是当前页
      if (id.value == 1) {
        pageData.btnList = []
        pageData.btnList1 = []
        pageData.isEdit = false
        if (permissionStore.hasPermisson('szdw.cx')) {
          pageData.btnList.push('查询')
        }
        if (permissionStore.hasPermisson('szdw.xz')) {
          pageData.btnList.push('新增')
        }
        if (permissionStore.hasPermisson('szdw.sc')) {
          pageData.btnList.push('删除')
        }
        if (permissionStore.hasPermisson('szdw.dc')) {
          pageData.btnList.push('导出')
        }
        if (permissionStore.hasPermisson('szdw.dr')) {
          tabBtnList.value.push('导入')
        }
        if (permissionStore.hasPermisson('shsc.mbxz')) {
          pageData.btnList.push('模板下载')
        }
        if (permissionStore.hasPermisson('szdw.xg')) {
          pageData.isEdit = true
        }
      } else {
        pageData.btnList = []
        pageData.btnList1 = []
        pageData.isEdit = false
        if (permissionStore.hasPermisson('sz.cx')) {
          pageData.btnList.push('查询')
        }
        if (permissionStore.hasPermisson('sz.xz')) {
          pageData.btnList.push('新增')
        }
        if (permissionStore.hasPermisson('sz.sc')) {
          pageData.btnList.push('删除')
        }
        if (permissionStore.hasPermisson('sz.dc')) {
          pageData.btnList.push('导出')
        }
        if (permissionStore.hasPermisson('sz.dr')) {
          pageData.btnList.push('导入')
        }
        if (permissionStore.hasPermisson('sz.mbxz')) {
          pageData.btnList.push('模板下载')
        }
        if (permissionStore.hasPermisson('sz.xg')) {
          pageData.isEdit = true
        }
      }
      //         如果单位是D，丹尼尔系数=输入的纱支数
      // 如果为S，丹尼尔系数=（590.9*9）/输入的纱支数,取两位小数位
      // 如果是双股S/2，丹尼乐系数=（590.9*9）/（输入的纱支数/2）,取两位小数位
      const changeNum = () => {
        if (dataForm.unit == 'D') {
          dataForm.coefficient = dataForm.num
        } else if (dataForm.unit == 'S') {
          dataForm.coefficient = parseFloat(((590.9 * 9) / dataForm.num).toFixed(2))
        } else if (dataForm.unit == 'S/2') {
          dataForm.coefficient = parseFloat(((590.9 * 9) / (dataForm.num / 2)).toFixed(2))
        }
      }
      const handleChange = (_data: any) => {
        if (id.value == 1) {
          tableList1 = _data
        } else {
          tableList2 = _data
        }
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const huiche = () => {
        pagination.page = 1
        cxbl = dataForm.yarnTypeNames
        doRefresh()
      }
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      return {
        colState,
        colState2,
        tabBtnList,
        permissionStore,
        shazhiguize,
        pagingList1,
        huiche,
        localeText1,
        isYarnCount,
        defaultColDef,
        tc,
        tc2,
        PageSize,
        change1,
        exportExcel,
        inputBlur1,
        isChiese,
        inputBlur,
        selectHanler,
        pageData3,
        editHandler1,
        isArr,
        szTyoeNames,
        szTypeName,
        tableColumns2,
        pageData2,
        id,
        editHandler,
        handoff,
        sideNo,
        sideNo2,
        deleteHandler,
        sideOk,
        sideOk1,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        paginations,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        options,
        loadings,
        options1,
        loading1,
        importHandler,
        downloadHandler,
        options12,
        loadings12,
        handleSearch12,
        headerShow,
        focusSel,
        changeNum,
        tableList1,
        tableList2,
        handleChange,
        // id,
        gridReady,
        gridReady2,
        table1Ref,
        configTable1,
        table2Ref,
        configTable2,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  .ag-theme-alpine {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
